package org.geektimes.projects.user.web.listener;

import org.geektimes.context.ComponentContext;
import org.geektimes.projects.user.management.ObjectShow2;
import org.geektimes.projects.user.management.ObjectShow;
import org.geektimes.projects.user.management.TargetObject;

import javax.management.*;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.lang.management.ManagementFactory;

public class DBConnectionInitializerListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ComponentContext context = new ComponentContext();
        context.init(sce.getServletContext());
        try {
            ObjectName objectName = new ObjectName("org.geektimes.projects.user.mannagement.ObjectShow:type=object1");
            ManagementFactory.getPlatformMBeanServer().registerMBean(new ObjectShow(new TargetObject()), objectName);
            ObjectName objectName2 = new ObjectName("org.geektimes.projects.user.mannagement.ObjectShow2:type=dynamic");
            BeanInfo beanInfo = Introspector.getBeanInfo(TargetObject.class);
            ManagementFactory.getPlatformMBeanServer().registerMBean(new ObjectShow2(new TargetObject(), beanInfo), objectName2);
        } catch (MalformedObjectNameException | NotCompliantMBeanException | InstanceAlreadyExistsException | MBeanRegistrationException | IntrospectionException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
